import { Component, ViewChild, Injector, EventEmitter, Output } from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { ScheduleServiceProxy, EquipmentSimpleListDto, BoundEquipmentsInput } from '@shared/service-proxies/service-proxies';
import { AppComponentBase } from '@shared/common/app-component-base';

import { DataTable } from 'primeng/components/datatable/datatable';
import { Paginator } from 'primeng/components/paginator/paginator';

import * as _ from 'lodash';
import { finalize } from 'rxjs/operators';

@Component({
    selector: 'boundEquipmentSchedulesModal',
    templateUrl: './bound-equipments-modal.component.html'
})
export class BoundEquipmentSchedulesModalComponent extends AppComponentBase {

    @ViewChild('editModal') modal: ModalDirective;
    @ViewChild('dataTableSchedule') dataTableSchedule: DataTable;
    @ViewChild('paginatorSchedule') paginatorSchedule: Paginator;

    @Output() modalSave: EventEmitter<any> = new EventEmitter<any>();

    active = false;
    saving = false;

    id: number;

    allEquipments: EquipmentSimpleListDto[];
    selectedEquipments: EquipmentSimpleListDto[];


    constructor(
        injector: Injector,
        private _scheduleService: ScheduleServiceProxy
    ) {
        super(injector);
    }

    show(id: number): void {
        this.id = id;
        this.active = true;

        this._scheduleService.getEquipmentsForBound(id).subscribe(result => {
            this.allEquipments = result.equipmentSimpleLists;
            this.selectedEquipments = result.selectedEquipmentSimpleLists;
            this.modal.show();
        });
    }

    save(): void {
        const input = new BoundEquipmentsInput();

        input.id = this.id;
        input.equipmentIds = this.selectedEquipments.map((el) => el.id);

        this.saving = true;

        this._scheduleService.boundEquipments(input)
        .pipe(finalize(() => this.saving = false))
            .subscribe(() => {
                this.notify.info(this.l('SavedSuccessfully'));
                this.close();
                this.modalSave.emit(null);
            });
    }

    close(): void {
      this.active = false;
        this.modal.hide();
    }
}
